<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const router = useRouter();
const loginType = ref('password'); // password 或 sms
const loading = ref(false);
const countdown = ref(0);
const timer = ref(null);
const captchaUrl = ref('');
const captchaKey = ref('');

// 密码登录表单
const passwordForm = reactive({
  phone: '',
  password: '',
  captcha: '',  // 图形验证码
});

// 短信验证码登录表单
const smsForm = reactive({
  phone: '',
  code: '',     // 短信验证码
  captcha: '',  // 图形验证码
});

const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入图形验证码', trigger: 'blur' }
  ]
};

const passwordFormRef = ref(null);
const smsFormRef = ref(null);

// 切换登录方式
const switchLoginType = (type) => {
  loginType.value = type;
  // 重新获取图形验证码
  refreshCaptcha();
};

// 获取图形验证码
const refreshCaptcha = async () => {
  try {
    // 生成随机uuid作为图形验证码的key
    captchaKey.value = 'captcha_' + Math.random().toString(36).substring(2);
    // 设置图形验证码URL
    captchaUrl.value = `http://localhost:8000/manage/image-code/?uuid=${captchaKey.value}`;
  } catch (error) {
    console.error('获取图形验证码失败', error);
    ElMessage.error('获取图形验证码失败');
  }
};

// 发送短信验证码
const sendSmsCode = async () => {
  // 验证手机号是否正确
  if (!smsForm.phone || !/^1[3-9]\d{9}$/.test(smsForm.phone)) {
    ElMessage.error('请输入正确的手机号');
    return;
  }
  
  // 验证图形验证码是否填写
  if (!smsForm.captcha) {
    ElMessage.error('请输入图形验证码');
    return;
  }
  
  // 发送短信验证码请求
  try {
    const response = await axios.post('http://localhost:8000/manage/send-code/', {
      phone: smsForm.phone,
      uuid: captchaKey.value,
      captcha: smsForm.captcha
    });
    
    const result = response.data;
    
    if (result.code === 200) {
      // 设置倒计时
      countdown.value = 60;
      timer.value = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(timer.value);
        }
      }, 1000);
      
      ElMessage.success('验证码已发送');
    } else {
      ElMessage.error(result.message || '发送验证码失败');
      // 刷新图形验证码
      refreshCaptcha();
    }
  } catch (error) {
    ElMessage.error('发送验证码失败');
    console.error(error);
    // 刷新图形验证码
    refreshCaptcha();
  }
};

// 登录处理
const handleLogin = async (formType) => {
  const formRef = formType === 'password' ? passwordFormRef.value : smsFormRef.value;
  const formData = formType === 'password' ? passwordForm : smsForm;
  
  if (!formRef) return;
  
  await formRef.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        // 根据不同的登录方式构建请求数据
        const loginData = formType === 'password' 
          ? { 
              phone: formData.phone, 
              password: formData.password, 
              login_type: "password",
              uuid: captchaKey.value,
              captcha: formData.captcha
            }
          : { 
              phone: formData.phone, 
              code: formData.code, 
              login_type: "sms",
              uuid: captchaKey.value,
              captcha: formData.captcha
            };
        
        // 发送登录请求
        const response = await axios.post('http://localhost:8000/manage/login/', loginData);
        
        const result = response.data;
        
        if (result.code === 200) {
          // 存储token和userid
          localStorage.setItem('token', result.data.token);
          localStorage.setItem('userid', result.data.userid);
          // 存储权限数据
          localStorage.setItem('permissions', JSON.stringify(result.data.permissions));
          // 存储用户信息
          localStorage.setItem('userInfo', JSON.stringify({
            name: result.data.name,
            phone: result.data.phone,
            role: result.data.role,
            department: result.data.department
          }));
          
          ElMessage.success('登录成功');
          // 登录成功后跳转到AboutView页面
          router.push('/about');
        } else {
          ElMessage.error(result.message || '登录失败');
          // 刷新图形验证码
          refreshCaptcha();
        }
      } catch (error) {
        ElMessage.error('登录请求失败');
        console.error(error);
        // 刷新图形验证码
        refreshCaptcha();
      } finally {
        loading.value = false;
      }
    }
  });
};

// 页面加载时获取图形验证码
onMounted(() => {
  refreshCaptcha();
});
</script>

<template>
  <div class="login-container">
    <div class="login-left">
      <div class="login-banner">
        <img src="https://img.freepik.com/free-vector/hospital-building-concept-illustration_114360-8440.jpg" alt="医院管理系统">
      </div>
    </div>
    <div class="login-right">
      <div class="login-form-container">
        <div class="login-header">
          <h1>七星医疗服务后台</h1>
          <p>专业医疗管理系统，高效服务患者</p>
        </div>
        
        <div class="login-tabs">
          <div 
            :class="['tab-item', { active: loginType === 'password' }]" 
            @click="switchLoginType('password')"
          >
            密码登录
          </div>
          <div 
            :class="['tab-item', { active: loginType === 'sms' }]" 
            @click="switchLoginType('sms')"
          >
            验证码登录
          </div>
        </div>
        
        <!-- 密码登录表单 -->
        <div v-show="loginType === 'password'" class="login-form">
          <el-form 
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="rules"
            label-width="0"
          >
            <el-form-item prop="phone">
              <el-input 
                v-model="passwordForm.phone"
                placeholder="请输入手机号"
                prefix-icon="Phone"
                size="large"
              />
            </el-form-item>
            
            <el-form-item prop="password">
              <el-input 
                v-model="passwordForm.password"
                type="password"
                placeholder="请输入密码"
                prefix-icon="Lock"
                show-password
                size="large"
              />
            </el-form-item>
            
            <el-form-item prop="captcha">
              <div class="captcha-container">
                <el-input 
                  v-model="passwordForm.captcha"
                  placeholder="请输入图形验证码"
                  prefix-icon="Key"
                  size="large"
                />
                <div class="captcha-img" @click="refreshCaptcha">
                  <img :src="captchaUrl" alt="验证码" v-if="captchaUrl" />
                </div>
              </div>
            </el-form-item>
            
            <el-form-item>
              <el-button 
                type="primary" 
                :loading="loading"
                @click="handleLogin('password')"
                class="login-button"
                size="large"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        
        <!-- 短信验证码登录表单 -->
        <div v-show="loginType === 'sms'" class="login-form">
          <el-form 
            ref="smsFormRef"
            :model="smsForm"
            :rules="rules"
            label-width="0"
          >
            <el-form-item prop="phone">
              <el-input 
                v-model="smsForm.phone"
                placeholder="请输入手机号"
                prefix-icon="Phone"
                size="large"
              />
            </el-form-item>
            
            <el-form-item prop="captcha">
              <div class="captcha-container">
                <el-input 
                  v-model="smsForm.captcha"
                  placeholder="请输入图形验证码"
                  prefix-icon="Key"
                  size="large"
                />
                <div class="captcha-img" @click="refreshCaptcha">
                  <img :src="captchaUrl" alt="验证码" v-if="captchaUrl" />
                </div>
              </div>
            </el-form-item>
            
            <el-form-item prop="code">
              <div class="code-input-container">
                <el-input 
                  v-model="smsForm.code"
                  placeholder="请输入短信验证码"
                  prefix-icon="Message"
                  size="large"
                />
                <el-button 
                  type="primary" 
                  class="send-code-btn"
                  :disabled="countdown > 0"
                  @click="sendSmsCode"
                  size="large"
                >
                  {{ countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码' }}
                </el-button>
              </div>
            </el-form-item>
            
            <el-form-item>
              <el-button 
                type="primary" 
                :loading="loading"
                @click="handleLogin('sms')"
                class="login-button"
                size="large"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        
        <div class="login-footer">
          <p>Copyright © 2023 七星医疗服务系统 All Rights Reserved</p>
        </div>
      </div>
    </div>
</div>
</template>

<style scoped>
.login-container {
  display: flex;
  height: 100vh;
  width: 100%;
  overflow: hidden;
  background-color: #f5f7fa;
}

.login-left {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #1890ff, #52c41a);
  padding: 20px;
}

.login-banner {
  width: 100%;
  max-width: 600px;
  height: auto;
}

.login-banner img {
  width: 100%;
  height: auto;
  object-fit: contain;
  border-radius: 8px;
}

.login-right {
  width: 500px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 40px;
  background-color: #fff;
  box-shadow: -4px 0 15px rgba(0, 0, 0, 0.1);
}

.login-form-container {
  width: 100%;
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.login-header h1 {
  font-size: 28px;
  color: #303133;
  margin-bottom: 10px;
}

.login-header p {
  font-size: 16px;
  color: #909399;
}

.login-tabs {
  display: flex;
  margin-bottom: 30px;
  border-bottom: 1px solid #dcdfe6;
}

.tab-item {
  flex: 1;
  padding: 15px 0;
  text-align: center;
  cursor: pointer;
  color: #606266;
  font-size: 16px;
  transition: all 0.3s;
}

.tab-item.active {
  color: #1890ff;
  border-bottom: 2px solid #1890ff;
  font-weight: 500;
}

.login-form {
  margin-bottom: 30px;
}

.code-input-container {
  display: flex;
  align-items: center;
}

.code-input-container .el-input {
  flex: 1;
  margin-right: 10px;
}

.send-code-btn {
  width: 130px;
  white-space: nowrap;
}

.captcha-container {
  display: flex;
  align-items: center;
}

.captcha-container .el-input {
  flex: 1;
  margin-right: 10px;
}

.captcha-img {
  width: 130px;
  height: 40px;
  cursor: pointer;
  overflow: hidden;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.captcha-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.login-button {
  width: 100%;
  height: 50px;
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 2px;
  margin-top: 10px;
}

.login-footer {
  text-align: center;
  color: #909399;
  font-size: 12px;
  margin-top: 20px;
}

@media (max-width: 992px) {
  .login-left {
    display: none;
  }
  
  .login-right {
    width: 100%;
  }
}
</style>
